package com.lry.basic.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadLocalVariableHolder {


    public static void setValue(int val) {
        variableHolder.set(val);
    }

    public static int getValue() {
        return variableHolder.get();
    }

    public static void remove() {
        variableHolder.remove();
    }

    public static void increment() {
        variableHolder.set(variableHolder.get() + 1);
    }

    //不复写initValue
    private static ThreadLocal<Integer> variableHolder = new InheritableThreadLocal<Integer>();

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        variableHolder.set(1);
        //线程池会复用线程，使用完线程后一定要清楚threadLocal，不然去执行新任务的时候会使用上一次的threadLocal产生错误结果
        for (int i = 0; i < 5; i++) {
            executor.execute(() -> {
                int before = getValue();//空指针
                try {
                    long threadId = Thread.currentThread().getId();
                    increment();
                    int after = getValue();
                    System.out.println("threadId: " + threadId + ", before: " + before + ", after: " + after);
                }finally {
//                    remove();
                    //恢复回去,方便下次线程复用时取出的值不变
                    variableHolder.set(before);
                }
            });
        }
        executor.shutdown();
    }
}